<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>AI Chat Test</title>
    <style>
        body { font-family: Arial, sans-serif; }
        #chat-container { width: 400px; margin: 50px auto; }
        .message { padding: 10px; margin-bottom: 10px; border-radius: 5px; }
        .user-message { background-color: #e6f7ff; }
        .ai-message { background-color: #ffe6cc; }
    </style>
</head>
<body>
<div id="chat-container">
    <div id="chat-history"></div>
    <form id="chat-form">
        <textarea id="message-input" rows="3" placeholder="Type your message here..." required></textarea>
        <br>
        <button type="submit">Send</button>
    </form>
</div>

<script>
document.getElementById('chat-form').addEventListener('submit', async function(event) {
    event.preventDefault();
    
    const input = document.getElementById('message-input');
    const chatHistory = document.getElementById('chat-history');

    // 添加用户消息到聊天历史
    const userMessageDiv = document.createElement('div');
    userMessageDiv.className = 'message user-message';
    userMessageDiv.textContent = input.value;
    chatHistory.appendChild(userMessageDiv);

    // 清空输入框
    input.value = '';

    // 发送消息到服务器
    try {
        const response = await fetch('http://localhost:3333/api/chat', {
            method: 'POST',
            headers: {
                'Content-Type': 'application/json'
            },
            body: JSON.stringify({ messages: [{ role: 'user', content: userMessageDiv.textContent }] })
        });

        const data = await response.json();

        // 添加AI回复到聊天历史
        const aiMessageDiv = document.createElement('div');
        aiMessageDiv.className = 'message ai-message';
        aiMessageDiv.textContent = data.choices[0].message.content;
        chatHistory.appendChild(aiMessageDiv);
    } catch (error) {
        console.error('Error:', error);
        alert('An error occurred while fetching the chat response.');
    }
});
</script>
</body>
</html>